package com.pi.shisan.web.util;

import com.pi.shisan.service.util.AppUtil;
import org.springframework.beans.BeansException;
import ws.schild.jave.Encoder;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;
import ws.schild.jave.process.ProcessLocator;

import java.io.File;

public class FormatConvert {

    private static volatile ProcessLocator processLocator;

    private static final ProcessLocator NULL_LOCATOR = () -> null;

    private static ProcessLocator getProcessLocator() {
        if (processLocator == null) {
            synchronized (FormatConvert.class) {
                if (processLocator == null) {
                    try {
                        processLocator = AppUtil.getApplicationContext().getBean(ProcessLocator.class);
                    } catch (BeansException e) {
                        processLocator = NULL_LOCATOR;
                    }
                }
            }
        }
        return processLocator;
    }

    public static void convertToMp3(File sourceFile, File targetFile) throws Exception{
        MultimediaObject multimediaObject = getProcessLocator() == NULL_LOCATOR ? new MultimediaObject(sourceFile): new MultimediaObject(sourceFile, getProcessLocator());
        AudioAttributes audioAttributes = new AudioAttributes();
        audioAttributes.setCodec("libmp3lame");
        audioAttributes.setBitRate(128000);
        audioAttributes.setChannels(2);
        audioAttributes.setSamplingRate(44100);
        EncodingAttributes encodingAttributes = new EncodingAttributes();
        encodingAttributes.setOutputFormat("mp3");
        encodingAttributes.setAudioAttributes(audioAttributes);
        Encoder encoder = getProcessLocator() == NULL_LOCATOR ? new Encoder() : new Encoder(getProcessLocator());
        encoder.encode(multimediaObject,targetFile,encodingAttributes);

    }

    public static void main(String[] args) throws Exception{
        convertToMp3(new File("E:/audio.m4s"), new File("a.mp3"));
    }

}